<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">选择收货地址</text>
      <view class="nav-right"></view>
    </view>
    
    <!-- 地址列表 -->
    <view class="address-list" v-if="!loading">
      <template v-if="addressList.length > 0">
        <view 
          v-for="(address, index) in addressList" 
          :key="address.id"
          class="address-item"
          :class="{ 'address-item-default': address.isDefault === 1 }"
          @click="selectAddress(address)"
        >
          <view class="address-content">
            <view class="address-header">
              <view class="address-name-phone">
                <text class="address-name">{{ address.receiverName }}</text>
                <text class="address-phone">{{ address.receiverPhone }}</text>
              </view>
              <view v-if="address.isDefault === 1" class="default-tag">默认</view>
            </view>
            <view class="address-detail">
              {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detailAddress }}
            </view>
          </view>
        </view>
      </template>
      
      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image class="empty-icon" src="/static/empty-address.png" mode="aspectFit"></image>
        <text class="empty-text">暂无收货地址</text>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <uni-load-more status="loading" :contentText="{ contentdown: '加载中...' }"></uni-load-more>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer">
      <button class="add-btn" @click="addNewAddress">
        <uni-icons type="plusempty" size="18" color="#FFFFFF"></uni-icons>
        <text>新增收货地址</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useUserStore } from '@/store/user';
import { useAddressStore } from '@/store/address';
import http from '@/utils/http/http.js';

const userStore = useUserStore();
const addressStore = useAddressStore();
const statusBarHeight = ref(0);
const addressList = ref([]);
const loading = ref(true);

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    // 使用 uni 对象前先声明
    statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight || 0;
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取地址列表
const fetchAddressList = async () => {
  if (!userStore.isLoggedIn || !userStore.token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
    return;
  }
  
  loading.value = true;
  
  try {
    const response = await http.get('/api/address/list', {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      addressList.value = response.data || [];
    } else {
      uni.showToast({
        title: response.message || '获取地址列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取地址列表失败:', error);
    uni.showToast({
      title: '获取地址列表失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 选择地址 - 修改为使用 store
const selectAddress = (address) => {
  // 使用 store 保存选中的地址
  addressStore.currentAddress = {
    id: address.id,
    receiverName: address.receiverName,
    receiverPhone: address.receiverPhone,
    receiverProvince: address.province,
    receiverCity: address.city,
    receiverDistrict: address.district,
    receiverAddress: address.detailAddress,
    isDefault: address.isDefault
  };
  
  // 返回上一页
  uni.navigateBack();
};

// 新增地址
const addNewAddress = () => {
  uni.navigateTo({
    url: '/pages/address/address-edit'
  });
};

// 页面加载
onMounted(() => {
  getStatusBarHeight();
  
  // 获取地址列表
  fetchAddressList();
  
  // 监听页面显示，用于编辑后刷新列表
  uni.$on('addressUpdated', fetchAddressList);
});

// 页面卸载
onUnmounted(() => {
  uni.$off('addressUpdated');
});
</script>

<style>
.container {
  padding-bottom: 120rpx;
  background-color: #FFF9F2;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #FFE6CC;
  padding: 0 20rpx;
}

.nav-back, .nav-right {
  width: 80rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 地址列表 */
.address-list {
  padding: 20rpx;
}

.address-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.address-item-default {
  border-left: 6rpx solid #FF8C42;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.address-name-phone {
  display: flex;
  align-items: center;
}

.address-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.address-phone {
  font-size: 28rpx;
  color: #666;
}

.default-tag {
  font-size: 22rpx;
  color: #fff;
  background-color: #FF8C42;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.address-detail {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载状态 */
.loading-state {
  padding: 40rpx 0;
}

/* 底部按钮 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.3);
}

.add-btn text {
  margin-left: 8rpx;
}
</style>